from model.hedging_models import HedgingCandle, HedgingInstInfo
from decimal import Decimal
from config.base_config import *
import datetime


def update_candle(inst_id: str, candle_data):
    '''
    更新k线
    :param inst_id: 产品id
    :param candle_data: k线数据
    :return:
    '''
    # 根据inst_id,s_time查询数据库
    s_time = int(candle_data[0])
    logging.info("inst_id=%s", inst_id)
    hedging_candle: HedgingCandle = HedgingCandle.select().where(
        (HedgingCandle.inst_id == inst_id) & (HedgingCandle.s_time == s_time)).limit(1).first()
    if hedging_candle is None:
        hedging_candle = HedgingCandle()
        hedging_candle.status = 0
    hedging_candle.inst_id = inst_id
    hedging_candle.s_time = s_time
    hedging_candle.o_price = Decimal(candle_data[1])
    hedging_candle.h_price = Decimal(candle_data[2])
    hedging_candle.l_price = Decimal(candle_data[3])
    hedging_candle.c_price = Decimal(candle_data[4])
    dt = datetime.datetime.fromtimestamp(s_time / 1000)
    hedging_candle.create_time = dt
    hedging_candle.save()


def delete_candle():
    # 删除10分钟以前的candle数据
    # 计算10分钟之前的时间
    ten_minutes_ago = datetime.datetime.now() - datetime.timedelta(minutes=10)
    query = HedgingCandle.delete().where(HedgingCandle.create_time < ten_minutes_ago)
    delete_count = query.execute()
    logging.info("删除了%s条数据", delete_count)


def get_subscribe_candles():
    inst_list = HedgingInstInfo.select().where(HedgingInstInfo.server_num == get_server_num())
    futures_info_list = []
    for inst_info in inst_list:
        futures_info = {
            'instType': "USDT-FUTURES",
            "channel": "candle1m",
            "instId": inst_info.inst_id
        }
        futures_info_list.append(futures_info)
    futures_candles = {
        "op": "subscribe",
        "args": futures_info_list
    }
    return futures_candles
